package org.apache.solr.ocean.util;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMDirectory;

public class RamDirectorySerializer {
	static final int BUFFER_SIZE = 16384;
	
  public RamDirectorySerializer() {
  }
  
  public static RAMDirectory deserialize(DataInput dataInput) throws IOException {
  	int numFiles = dataInput.readInt();
  	RAMDirectory ramDirectory = new RAMDirectory();
  	byte[] buffer = new byte[BUFFER_SIZE];
  	for (int x=0; x < numFiles; x++) {
  		String file = dataInput.readUTF();
  		int length = dataInput.readInt();
  		IndexOutput indexOutput = ramDirectory.createOutput(file);
  		int readCount = 0;
      while (readCount < length) {
        int toRead = readCount + BUFFER_SIZE > length ? (int)(length - readCount) : BUFFER_SIZE;
        dataInput.readFully(buffer, 0, toRead);
        indexOutput.writeBytes(buffer, toRead);
        readCount += toRead;
      }
      indexOutput.close();
  	}
  	return ramDirectory;
  }
  
  public static void serialize(RAMDirectory ramDirectory, DataOutput dataOutput) throws IOException {
  	String[] files = ramDirectory.list();
  	dataOutput.writeInt(files.length);
  	byte[] buffer = new byte[BUFFER_SIZE];
  	for (String file : files) {
  		int length = (int)ramDirectory.fileLength(file);
  		dataOutput.writeUTF(file);
  		dataOutput.writeInt(length);
  		IndexInput indexInput = ramDirectory.openInput(file);
  		int readCount = 0;
      while (readCount < length) {
        int toRead = readCount + BUFFER_SIZE > length ? (int)(length - readCount) : BUFFER_SIZE;
        indexInput.readBytes(buffer, 0, toRead);
        dataOutput.write(buffer, 0, toRead);
        readCount += toRead;
      }
      indexInput.close();
  	}
  }
}
